<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 警告信息 -->
      <el-alert
        title="注意：只允许为第三级分类设置参数"
        type="warning"
        effect="dark"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="selectedGoodCate">
        <el-col>
          <!-- 选择商品分类标签 -->
          <span>选择商品分类:</span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签 -->
      <el-tabs v-model="activeName" @tab-click="handleTagsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisbled"
            @click="addParamsDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" border stripe>
            <!-- 扩展列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="tag"
                  v-for="(tag, index) in scope.row.attr_vals"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 添加新标签input -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加新标签tag -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisbled"
            @click="addParamsDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 扩展列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="tag"
                  v-for="(tag, index) in scope.row.attr_vals"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 添加新标签input -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加新标签tag -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数、静态属性弹窗 -->
    <el-dialog
      :title="'添加' + activeTitle"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsFormClosed"
    >
      <!-- 对话框主体区域 -->
      <el-form
        :model="addParamsForm"
        :rules="ParamsFormRules"
        ref="addParamsFormRef"
        label-width="70px"
      >
        <el-form-item :label="activeTitle" prop="attr_name" label-width="100px">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑动态参数、静态属性弹窗 -->
    <el-dialog
      :title="'编辑' + activeTitle"
      :visible.sync="editParamsDialogVisible"
      width="50%"
    >
      <!-- 对话框主体区域 -->
      <el-form
        :model="editParamsForm"
        :rules="ParamsFormRules"
        ref="editParamsFormRef"
        label-width="70px"
      >
        <el-form-item :label="activeTitle" prop="attr_name" label-width="100px">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: null,
      // 级联选择器配置
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器选中的id
      selectedKeys: [],
      // tab页签激活页名称
      activeName: 'many',
      // 动态tab栏参数
      manyTabData: null,
      // 静态tab栏参数
      onlyTabData: null,
      // 添加参数弹窗可见
      addParamsDialogVisible: false,
      // 添加参数表单数据
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数表单验证规则
      ParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 编辑参数弹窗可见
      editParamsDialogVisible: false,
      // 编辑参数表单数据
      editParamsForm: {
        attr_name: ''
      },
      // 参数属性id
      attrId: null,
      // 添加tag标签input可见
      inputVisible: false,
      // 新标签名
      inputValue: ''
    }
  },
  created() {
    //   获取商品分类列表
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      this.cateList = res.data
    },
    // 当级联选择器选择发生改变时
    handleChange() {
      this.getParamsData()
    },
    //  点击tab栏切换事件
    handleTagsClick() {
      this.getParamsData()
    },
    // 获取参数列表数据
    async getParamsData() {
      // 如果选择的不是三级分类则清空当前选择
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return true
      }
      // 根据当前选择的分类和面板发起对应请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败')
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      // 根据tab栏不同存储数据
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    // 添加参数弹窗关闭事件
    addParamsFormClosed() {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 添加参数
    addParams() {
      // 表单预验证
      this.$refs.addParamsFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('添加参数表单验证失败，请重新填写')
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('成功添加参数')
        this.addParamsDialogVisible = false
        this.getParamsData()
      })
    },
    // 显示编辑参数弹窗
    async showEditParamsDialog(attrId) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          attr_sel: this.activeName
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数数据失败')
      }
      this.editParamsForm.attr_name = res.data.attr_name
      this.attrId = attrId
      this.editParamsDialogVisible = true
    },
    // 修改参数
    editParams() {
      // 表单预验证
      this.$refs.editParamsFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('编辑参数表单验证失败，请重新填写')
        }
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.attrId}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑参数失败')
        }
        this.$message.success('成功编辑参数')
        this.editParamsDialogVisible = false
        this.getParamsData()
      })
    },
    // 删除参数
    removeParams(attrId) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${attrId}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除参数失败')
          }
          this.$message({
            type: 'success',
            message: '成功删除参数!'
          })
          this.getParamsData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // input失去焦点和按下enter键触发事件
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return row.inputVisible
      }
      row.attr_vals.push(row.inputValue)
      row.inputVisible = false
      row.inputValue = ''
      // 发起请求，保存修改的参数数据
      this.saveParamsData(row)
    },
    // 展示input
    showInput(row) {
      row.inputVisible = true
      // 输入框自动获取焦点
      // $nextTick当页面上的元素重新被渲染后执行其中代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 发起请求，保存修改的参数数据
    async saveParamsData(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('成功修改参数')
    },
    // 删除tag标签
    handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveParamsData(row)
    }
  },
  computed: {
    //   如果没有选择三级分类，则按钮被禁用
    isBtnDisbled() {
      if (this.selectedKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 获得当前选择的三级分类Id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 计算当前添加弹窗的title值
    activeTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.selectedGoodCate {
  margin: 15px 0;
}
.selectedGoodCate span {
  margin-right: 15px;
}
.el-tag {
  margin-left: 15px !important;
}
.button-new-tag,
.input-new-tag {
  margin-left: 15px !important;
}
.input-new-tag {
  width: 120px;
}
</style>
